/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.service.log.impl;

import com.je.auth.AuthLoginManager;
import com.je.auth.AuthSessionTemplate;
import com.je.common.auth.impl.DepartmentUser;
import com.je.common.auth.impl.account.Account;
import com.je.common.base.DynaBean;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.SystemSettingRpcService;
import com.je.common.base.util.DateUtils;
import com.je.common.base.util.StringUtil;
import com.je.rbac.exception.LoginException;
import com.je.rbac.service.account.RbacLoginService;
import com.je.rbac.service.log.RbacBuryLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class RbacBuryLogServiceImpl implements RbacBuryLogService {

    @Autowired
    private AuthLoginManager authLoginManager;
    @Autowired
    private AuthSessionTemplate authSessionTemplate;
    @Autowired
    private MetaService metaService;
    @Autowired
    private RbacLoginService rbacLoginService;
    @Autowired
    private SystemSettingRpcService systemSettingRpcService;

    @Override
    public void bury(String typeCode, String typeName, String objCode, String objName) throws LoginException {
        if (!rbacLoginService.checkLogin()) {
            throw new LoginException("请先登录！");
        }
        String JE_SYS_LOGINFO = systemSettingRpcService.findSettingValue("JE_SYS_LOGINFO");
        if(StringUtil.isEmpty(JE_SYS_LOGINFO)||(JE_SYS_LOGINFO.split(",").length==0)){
            return;
        }
        List<String> list = Arrays.asList(JE_SYS_LOGINFO.split(","));
        if(!list.contains("JE_SYS_VISITLOG")){
            return;
        }
        Account account = (Account) authSessionTemplate.get(authLoginManager.getSession(), "account");
        DynaBean logBean = new DynaBean("JE_RBAC_BURY", false);
        logBean.set("BURY_OBJECT_CODE", objCode);
        logBean.set("BURY_OBJECT_NAME", objName);
        logBean.set("BURY_TYPE_CODE", typeCode);
        logBean.set("BURY_TYPE_NAME", typeName);
        logBean.set("JE_RBAC_ACCOUNT_ID", account.getId());
        logBean.set("BURY_ACCOUNT_NAME", account.getName());
        logBean.set("SY_ORG_ID", account.getPlatformOrganization().getId());
        if (account.getRealUser() != null && account.getRealUser() instanceof DepartmentUser) {
            DepartmentUser departmentUser = (DepartmentUser) account.getRealUser();
            logBean.set("SY_COMPANY_ID", departmentUser.getCompanyId());
            logBean.set("SY_COMPANY_NAME", departmentUser.getCompanyName());
            logBean.set("SY_GROUP_COMPANY_ID", departmentUser.getGroupCompanyId());
            logBean.set("SY_GROUP_COMPANY_NAME", departmentUser.getGroupCompanyName());
        }
        logBean.set("SY_CREATETIME", DateUtils.formatDateTime(new Date()));
        metaService.insert(logBean);
    }

    @Override
    public Map<String, Object> findBuryList(int start, int limit, boolean dateSerch) {
        List<Map<String, Object>> records;
        long count=0;
        if(dateSerch){
            //两小时内活跃查询
            SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DAFAULT_DATETIME_FORMAT);
            //当前日期
            String dateStr = sdf.format(new Date());
            //两个小时前的时间
            String beforeDateStr = getBeforeHourTime(2);

             records = metaService.selectSql(Integer.valueOf(start), Integer.valueOf(limit), "SELECT bury.JE_RBAC_ACCOUNT_ID, bury.BURY_ACCOUNT_NAME,bury.SY_CREATETIME,account.ACCOUNT_AVATAR FROM JE_RBAC_BURY bury , je_rbac_account account where bury.JE_RBAC_ACCOUNT_ID = account.JE_RBAC_ACCOUNT_ID AND bury.SY_CREATETIME BETWEEN {0} AND {1} GROUP BY bury.JE_RBAC_ACCOUNT_ID  ORDER BY bury.SY_CREATETIME DESC",beforeDateStr,dateStr);
             count = metaService.countBySql("SELECT bury.JE_RBAC_ACCOUNT_ID FROM JE_RBAC_BURY bury WHERE bury.SY_CREATETIME BETWEEN {0} AND {1} GROUP BY bury.JE_RBAC_ACCOUNT_ID",beforeDateStr,dateStr);
        }else{
             records = metaService.selectSql(Integer.valueOf(start), Integer.valueOf(limit), "SELECT bury.*,account.ACCOUNT_AVATAR FROM JE_RBAC_BURY bury , je_rbac_account account where bury.JE_RBAC_ACCOUNT_ID = account.JE_RBAC_ACCOUNT_ID order by bury.SY_CREATETIME desc");
             count = metaService.countBySql("SELECT bury.JE_RBAC_ACCOUNT_ID FROM JE_RBAC_BURY bury");
        }
        Map<String, Object> result = new HashMap<>();
        result.put("records", records);
        result.put("total", count);
        result.put("start", start);
        result.put("limit", limit);
        return result;
    }


    /**
     * 获取当前时间前几个小时的时间
     *
     * @param ihour
     * @return
     */
    public static String getBeforeHourTime(int ihour) {
        String returnstr = "";
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - ihour);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        returnstr = sdf.format(calendar.getTime());

        return returnstr;
    }

}